package com.youtui.manager.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.youtui.common.constant.ResultMessage;
import com.youtui.common.util.JsonUtil;
import com.youtui.common.util.JwtTokenUtil;
import com.youtui.common.util.ResultUtil;

public class LoginContextInterceptor implements HandlerInterceptor {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	JwtTokenUtil jwtTokenUtil;
	
	private static List<String> preInterceptorUrls = new ArrayList<String>(); 

	public static List<String> getPreInterceptorUrls() {
		return preInterceptorUrls;
	}

	public static void setPreInterceptorUrls(List<String> preInterceptorUrls) {
		LoginContextInterceptor.preInterceptorUrls = preInterceptorUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI();
		logger.debug("URI:"+uri);
		for (String preInterceptorUrl : preInterceptorUrls) {
            if (uri.indexOf(preInterceptorUrl)>=0) {
                 return true;
            }
        }
  
		String token = request.getHeader("token");
		if(token == null){
			token =request.getParameter("token");   // 头部没有使用参数
		}
		Map<String, Object> map = jwtTokenUtil.verifyJwtToken(token);
		if (map != null) {
			return true;
		} else {
			ResultMessage result = ResultUtil.result(-500, "登录超时");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.append(JsonUtil.getJSONString(result));
			} catch (IOException ie) {
				ie.printStackTrace();
			} finally {
				if (out != null) {
					out.close();
				}
			}
			return false;

		}
 
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
